﻿//Author : Sabry Moulana

// === Constants ===
var gridName = "#dvMainGrid";

// === End Constants ==
// variable that represents the captcha, whether it is
// successful or not



// Method for the autocomplete to execute
// using the web api method
$(function () {
    $("#txtSearch").bind("enterKey", function (e) {
        $('gridName').empty();

        RenderMainGrid();
    }).keyup(function (e) {
        if (e.keyCode === 13) {
            // hide the autocomplete dropdown once the enter key 
            // has been pressed
            $(".ui-menu-item").hide();

            // trigger the enter key binding function
            $(this).trigger("enterKey");
        }
    }).autocomplete({
        source: function (request, response) {

            $.ajax({
                url: '/search/autocomplete',
                type: 'GET',
                cache: false,
                data: request,
                dataType: 'json',
                success: function (json) {
                    // call autocomplete callback method with results  
                    response($.map(json, function (Object) {
                        return {
                            label: Object.Value,
                            value: Object.Key
                        }
                    }));
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log('error', textStatus, errorThrown);
                }
            });

        },
        focus: function (event, ui) {
            this.value = ui.item.label;
            event.preventDefault(); // Prevent the default focus behavior.
        },
        minLength: 4,
        select: function (event, ui) {
            //  alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
            $('#txtSearch').val(ui.item.label);
            $('gridName').empty();
            var crudServiceBaseUrl = "/search/standardsearch";

            RenderMainGrid();

            return false;
        }
    });
});

// method that validates the captcha
function Captcha() {
    var captchaSuccess = false;
    $('#status').attr('class', 'inProgress');
    $('#status').text('Checking...');

    // get client-side Captcha object instance
    var captchaObj = $("#CaptchaCode").get(0).Captcha;

    // gather data required for Captcha validation
    var params = {}
    params.CaptchaId = captchaObj.Id;
    params.InstanceId = captchaObj.InstanceId;
    params.UserInput = $("#CaptchaCode").val();

    $.ajax({
        url: 'CheckCaptcha',
        dataType: 'json',
        async: false,
        data: params,
        success: function (result) {
            //stuff
            if (true === result) {
                $('#status').attr('class', 'correct');
                $('#status').text('Check passed');

            } else {
                $('#status').attr('class', 'incorrect');
                $('#status').text('Check failed');

                // always change Captcha code if validation fails
                captchaObj.ReloadImage();
            }
            captchaSuccess = result;
        }
    });

    return captchaSuccess;
}



$(document).ready(function () {
    //$("#menu1").wijmenu({ trigger: ".wijmo-wijmenu-item", triggerEvent: "click" });

    // before the login button submits check the captcha with a synchronous call
    $("#btnLogin").click(function (evt) {
        if (($("#txtbxPassword").val().length > 5) && ($("#txtbxUsername").val().length > 0)) {

            var captchaValue = Captcha();

            // if the captcha returns false then the default submit action is stopped 
            if (captchaValue === false) {
                evt.preventDefault();
            }
        }
    });

			


    $(".accordion").accordion({
        collapsible: true,
        header: "h3",
        active: -1
    });

    // $("#frmAddEmployee").validate();


    $("#frmNewEmployee").hide();




    // Get the employee number from the DB 
    $("#clickMe").click(function () {
        var defaultValue;
        if ($("#frmNewEmployee").is(':visible') === false) {
            var parameters = { UserId: '' }
            $("#frmNewEmployee").show();

        }
        else {
            $("#frmNewEmployee").hide();
        }

    });

    $('#btnAddNewEmployee').click(function () {
        // $('.ui-dialog').css("top", "110px");
        $('#wiji').dialog('open');
        return false;
    });

    $('#dvMoreDetail').buttonset();
    $('#dvAdditionalDepartmentInfo').buttonset();

    $('#dvMoreDetail input[type=radio]').change(function () {

        RenderProfileSalaryAndTitleGrid(this.value, $("#pEmployeeNumber").html());
    })

    $('#dvAdditionalDepartmentInfo input[type=radio]').change(function () {

        $('gridName').empty();
        $('#chart').empty();
        if (eval(this.value) > 0) {
            RenderMainGrid($("#pdepartmentNumber").html(), (eval(this.value) === 2) ? true : false);
        }
        else {

            var chartData;
            var chartTitle;
            $.ajax({
                type: "GET",
                url: "/Department/GenerateDepartmentBasedGenderDemographic?departmentNumber=" + $("#pdepartmentNumber").html(),
                data: null,//JSON.stringify(jsonPacket.employee),
                contentType: 'application/json; charset=utf-8',
                async: false,
                success: function (result) {
                    if (result !== undefined) {
                        chartData = result.Data;
                        chartTitle = result.ChartTitle;
                    }
                    else {
                        alert(result.Success);
                        $(this).dialog("close");
                    }

                },
                error: function (e) {
                    alert(e);
                }
            });
            setTimeout(function () {
                // Initialize the chart with a delay to make sure
                // the initial animation is visible
                createChart(chartData, chartTitle);

                $("#example").bind("kendo:skinChange", function (e) {
                    createChart(chartData, chartTitle);
                });
            }, 400);
        }
    })



    $('#wiji').dialog({
        autoOpen: false,
        width: 600,
        //height: 460,
        title: "Add New Employee",
        buttons: {
            "Submit": function () {
                var $myForm = $('#frmAddEmployee')
                if (!$myForm[0].checkValidity()) {
                    // If the form is invalid, submit it. The form won't actually submit;
                    // this will just cause the browser to display the native HTML5 error messages.
                    $myForm.find(':submit').click()
                }
                else {
                    // $(this).dialog("close");
                    var jsonPacket = form2js(document.getElementById('frmAddEmployee'));
                    alert(jsonPacket);
                    $.ajax({
                        type: "POST",
                        url: "/Employee/Create",
                        data: JSON.stringify(jsonPacket.employee),
                        contentType: 'application/json; charset=utf-8',
                        async: false,
                        success: function (result) {
                            if (result.Success === true) {
                                if ($(gridName).data("kendoGrid") !== undefined) {
                                    console.log("success");
                                    $(gridName).data("kendoGrid").dataSource.read();
                                }
                                $(this).dialog("close");
                            }
                            else {
                                alert(result.Success);
                                $(this).dialog("close");
                            }

                        },
                        error: function (e) {
                            alert(e);
                        }
                    });
                    $(this).dialog("close");
                }

            },
            "Cancel": function () {
                $(this).dialog("close");
            }
        }
    });


    // Datepicker
    $("#birthDate").datepicker(
        {
            inline: true,
            minDate: '-65Y',
            maxDate: '-18Y'

        });

    $('#hireDate').datepicker({
        inline: true,
        minDate: '-1M',
        maxDate: '+1W'
    });
  
   
    // end of document.ready
});






// function that renders the main grid that is used in both 
// authenticated and unauthenticated search
function RenderMainGrid(departmentNumber, showOldEmployee) {
    var crudServiceBaseUrl = "/search/standardsearch";
    var showConfidential;
    var isAdmin;

    if (departmentNumber !== undefined) {

        showConfidential = false;
        isAdmin = false;


    }
    else {
        $.ajax({
            type: "GET",
            url: "/Employee/GetAuthentication",
            data: null,
            contentType: 'application/json; charset=utf-8',
            async: false,
            success: function (result) {
                if ((result.isAdmin !== undefined) && (result.isConfidential !== undefined)) {
                    showConfidential = result.isConfidential;
                    isAdmin = result.isAdmin;
                }
                else {
                    alert("Failed");
                }

            },
            error: function (e) {
                alert(e);
            }
        });
    }

    var kendoDataSource = new kendo.data.DataSource({
        // the transport tells the datasource what endpoints
        // to use for CRUD actions
        transport: {
            read: {
                url: crudServiceBaseUrl,
                type: "POST",
                contentType: "application/json"
            },
            update: {
                // get the id off of the model object that
                // kendo ui automatically passes to the url function
                url: function (employee) {
                    return "/employee/edit?employeeNumber=" + employee.employeeNumber
                },

                type: "POST",
                dataType: "json"
            },
            destroy: {
                // get the id off of the model object that
                // kendo ui automatically passes to the url function
                url: function (employee) {
                    return "/employee/delete/" + employee.employeeNumber
                },
                type: "DELETE"
            },
            parameterMap: function (options, operation) {
                if (operation === "read") {

                    var extendedK = new ExtendedKendo();
                    extendedK.ParseOriginalKendo(options, null, null, departmentNumber, showOldEmployee);

                    // convert the parameters to a json object
                    return kendo.stringify(extendedK);
                }

                // ALWAYS return options
                return options;
            }
        },
        // the schema defines the schema of the JSON coming
        // back from the server so the datasource can parse it
        schema: {
            // the array of repeating data elements (employees)
            data: "Data",
            // the total count of records in the whole dataset. used
            // for paging.
            total: "Count",

            model: {

                id: "employeeNumber",

                fields: {

                    employeeNumber: { type: "number", editable: false, nullable: false },

                    firstName: { editable: false, validation: { required: true } },

                    lastName: { validation: { required: true } },

                    gender: { editable: false, validation: { required: true } },

                    birthDate: { type: "date", editable: false },
                    
                    hireDate: { type: "date", editable: false }

                }
            },

            // map the errors if there are any. this automatically raises the "error" 
            // event
            errors: "Errors"
        },
        error: function (e) {

            console.log(e.statusText);
        },
        // the number of records to show per page
        pageSize: 20,
        // do paging on the server
        serverPaging: true,
        // do sorting on the server
        serverSorting: true,

    });


    $(gridName).kendoGrid({
        // specify the columns on the grid
        columns: [

            { field: "employeeNumber", title: "Employee No", width: "100px" },

            { field: "firstName", title: "First Name", width: "150px" },

            { field: "lastName", title: "Last Name", width: "150px" },

            { field: "gender", title: "Gender", width: "75px" },

            { field: "birthDate", title: "Birth Date", width: "100px", template: '#= kendo.toString(birthDate,"MM/dd/yyyy") #' },

            { field: "hireDate", title: "Hire Date", width: "100px", template: '#= kendo.toString(hireDate,"MM/dd/yyyy") #' },

            {

                command: (isAdmin === true) ? ["edit", "destroy"] : null,
                title: (isAdmin === true) ? "&nbsp;" : null,
                width: (isAdmin === true) ? "210px" : null
            },
             { command: { text: "Profile Picture", click: showImage }, title: " ", width: "100px" }

        ],


        detailTemplate: (showConfidential === true) ? kendo.template($("#template").html()) : null,

        // the datasource for the grid
        dataSource: kendoDataSource,

        // paging is enabled in the grid
        pageable: true,
        // editing happens inline, one row at a time.

        editable: (isAdmin === true) ? "popup" : null,

        edit: function (e) {
            var editWindow = this.editable.element.data("kendoWindow");
            editWindow.wrapper.css({ transform: "scale(1)" });
            editWindow.wrapper.css("-webkit-transform", "");
        },

        // filterable: true,

        selectable: true,

        // sort by multiple columns
        sortable: {
            mode: "multiple"
        },

        resizable : true,

        detailInit: (showConfidential === true) ? detailInit : null,

        change: function (e) {
            // get the current item selected in the grid
            var employee = this.dataSource.getByUid(this.select().data("uid"));
            // write out the employee id

            // console.log(employee.id);
        }
    });

    if (isConfidential = true) {
        $(gridName).data('kendoGrid').hideColumn('birthDate');
        $(gridName).data('kendoGrid').hideColumn('hireDate');
    }
   


    // Detail init function for the first kendo grid
    function detailInit(e) {

        var detailRow = e.detailRow;
        var employeeNumber = e.data.employeeNumber;


        var tabIndex = 1;

        detailRow.find("#tabstrip").kendoTabStrip();

        if (isAdmin === true) {
            detailRow.find("#salaryDetails").kendoGrid({
                dataSource: {
                    type: "json",
                    transport:
                        {
                            read: {
                                url: "/Employee/GetSalaryLog/",
                                type: "POST",
                                contentType: "application/json"
                            }
                            ,
                            create: {
                                url: "/Employee/AddSalary/",
                                type: "POST",
                                contentType: "application/json",
                                complete: function (e) {
                                    $("#salaryDetails").data("kendoGrid").dataSource.read();
                                }

                            },
                            parameterMap: function (options, operation, e) {
                                if (operation === "read") {

                                    var extendedK = new ExtendedKendo();
                                    extendedK.ParseOriginalKendo(options, true, employeeNumber);

                                    // convert the parameters to a json object
                                    return kendo.stringify(extendedK);
                                }
                                if (operation === "create") {
                                    var d = new Date(options.toDate);
                                    options.employeeNumber = employeeNumber;
                                    options.toDate = kendo.toString(new Date(d), "MM/dd/yyyy");
                                    d = new Date(options.fromDate);
                                    options.fromDate = kendo.toString(new Date(d), "MM/dd/yyyy");
                                    return kendo.stringify(options);
                                }
                                // ALWAYS return options
                                return options;
                            }
                        },
                    schema: {

                        // the array of repeating data elements (employees)
                        data: "Data",

                        // the total count of records in the whole dataset. used
                        // for paging.
                        total: "Count",
                        model: {
                            id: "employeeNumber",

                            fields: {

                                employeeNumber: { type: "number", editable: false, nullable: false },

                                salary: {
                                    type: "number",
                                    validation: {
                                        required: true,
                                        salaryCheck: function (input) {
                                            if (input.attr("name") == "salary") {
                                                input.attr("data-ageCheck-msg", "The minimum salary payable to an employee is $9000.00");

                                                // check if the input value is greater than 8000
                                                return input.val() > 8000;
                                            }
                                            return true;
                                        }
                                    }
                                },

                                fromDate: { type: "date" },

                                toDate: { type: "date" }

                            }

                        },

                        parse: function (response) {
                            if (response.Data !== undefined) {
                                for (var i = 0; i < response.Data.length; i++) {
                                    response.Data[i].toDate;
                                    if (response.Data[i].toDate !== undefined) {
                                        if (response.Data[i].toDate === "/Date(253370745000000)/") {
                                            response.Data[i].toDate = null;
                                        }
                                    }

                                }
                            }
                         
                            return response;
                        },

                        error: errorHandle(e, this),
                    },

                    serverPaging: true,

                    serverSorting: true,

                    serverFiltering: true,

                    pageSize: 6

                },

                requestEnd: onRequestEnd(e, this),

                pageable: true,
                
                toolbar: ["create", {
                    name: 'removeLastSalary', template: '#= RemoveSalary()#'
                        // '<a class="k-button" href="#" id="lnkRemove">Remove Last Salary </a>'
                }],

                editable: {

                    mode: "popup",
                    template: $("#popupeditor").html()
                },

                edit: function (e) {
                    var editWindow = this.editable.element.data("kendoWindow");
                    editWindow.wrapper.css({ transform: "scale(1)" });
                    editWindow.wrapper.css("-webkit-transform", "");

                },


                columns: [
                    { field: "salary", title: "Salary", format: "{0:c}" },

                    { field: "fromDate", title: "Start Date", template: '#= kendo.toString(fromDate,"MM/dd/yyyy") #' },

                    { field: "toDate", title: "End Date", template: "#= (toDate == null) ? 'Current' : kendo.toString(toDate, 'MM/dd/yyyy') #" }
                ]
            });
        }
        else {

            $("#tabstrip-1").remove();
            $("li").remove(":contains('Salary History')");

        }

        detailRow.find("#titleHistory").kendoGrid({
            dataSource: {
                type: "json",
                transport:
                    {
                        read: {
                            url: "/Employee/GetTitleLog/",
                            type: "POST",
                            contentType: "application/json"
                        },
                        create: {
                            url: "/Employee/AddTitle/",
                            type: "POST",
                            contentType: "application/json",
                            complete: function (e) {
                                $("#titleHistory").data("kendoGrid").dataSource.read();
                            }},
                        parameterMap: function (options, operation, e) {
                            if (operation === "read") {

                                var extendedK = new ExtendedKendo();
                                extendedK.ParseOriginalKendo(options, true, employeeNumber);
                                // convert the parameters to a json object
                                return kendo.stringify(extendedK);
                            }
                            // if the current operation is an update
                            if (operation === "create") {
                                var d = new Date(options.toDate);
                                options.employeeNumber = employeeNumber;
                                options.toDate = kendo.toString(new Date(d), "MM/dd/yyyy");
                                d = new Date(options.fromDate);
                                options.fromDate = kendo.toString(new Date(d), "MM/dd/yyyy");
                                return kendo.stringify(options);
                            }

                            // ALWAYS return options
                            return options;
                        }
                    },
                schema: {
                    // the array of repeating data elements (employees)
                    data: "Data",

                    // the total count of records in the whole dataset. used
                    // for paging.
                    total: "Count",
                    model: {
                        id: "employeeNumber",

                        fields: {

                            employeeNumber: { type: "number", editable: false, nullable: false },

                            // department: { editable: false },

                            fromDate: { type: "date" },

                            toDate: { type: "date" },

                            title: {
                                editable: true
                            },

                            // Category: { defaultValue: { CategoryID: 1, CategoryName: "Beverages"} }
                        }

                    },

                    parse: function (response) {
                        if (response.Data !== undefined) {
                            for (var i = 0; i < response.Data.length; i++) {
                                response.Data[i].toDate;
                                if (response.Data[i].toDate !== undefined) {
                                    if (response.Data[i].toDate === "/Date(253370745000000)/") {
                                        response.Data[i].toDate = null;
                                    }
                                }

                            }
                        }
                        return response;
                    }

                },

                serverPaging: true,

                serverSorting: true,

                serverFiltering: true,

                pageSize: 6,
            },

            toolbar: ["create", {
                name: 'Remove Last Title', template: '#= RemoveTitle()#'
                // '<a class="k-button" href="#" id="lnkRemove">Remove Last Salary </a>'
            }],

            pageable: true,

            // height: 200,

            columns: [
                { field: "title", title: "Title" }, // , editor: categoryDropDownEditor

                { field: "fromDate", title: "Start Date", template: '#= kendo.toString(fromDate,"MM/dd/yyyy") #' },                

                { field: "toDate", title: "End Date", template: "#= (toDate == null) ? 'Current' : kendo.toString(toDate, 'MM/dd/yyyy') #" }
            ],

            editable: {

            mode: "popup",
                template: $("#titleCreateTemplate").html()
            },
            edit: function (e) {
                var editWindow = this.editable.element.data("kendoWindow");
                $(".k-window-title").html("Add New Title");
                editWindow.wrapper.css({ transform: "scale(1)" });
                editWindow.wrapper.css("-webkit-transform", "");
                $("#select").kendoComboBox();
            }

        });
    }

}

function RenderProfileSalaryAndTitleGrid(active, employeeNumber) {

    var readUrl;
    var columns;
    var gridColumns;
    $("#dvAdditional").empty();
    if (active === "0") {

        readUrl = "/employee/GetSalaryLog";
        columns = {

            // employeeNumber: { editable: false, visible: false },

            salary: { editable: false },

            fromDate: { editable: false, type: "date" },

            toDate: { editable: false, type: "date" }

        };

        gridColumns = [
              { field: "salary", title: "Salary" },

              { field: "fromDate", title: "Start Date", template: '#= kendo.toString(fromDate,"MM/dd/yyyy") #' },

              { field: "toDate", title: "End Date", template: "#= (toDate == null) ? 'Current' : kendo.toString(toDate, 'MM/dd/yyyy') #" }
        ];
    }
    else if (active === "1") {


        readUrl = "/employee/GetTitleLog";
        columns = {

            // employeeNumber: { editable: false, visible: false },

            salary: { editable: false },

            fromDate: { editable: false, type: "date" },

            toDate: { editable: false, type: "date" }

        };

        gridColumns = [
                { field: "title", title: "Title" },

                { field: "fromDate", title: "Start Date", template: '#= kendo.toString(fromDate,"MM/dd/yyyy") #' },

                { field: "toDate", title: "End Date", template: "#= (toDate == null) ? 'Current' : kendo.toString(toDate, 'MM/dd/yyyy') #" }
        ];
    }

    // Declare and initialize the data source
    var source = new kendo.data.DataSource({
        // the transport tells the datasource what endpoints
        // to use for CRUD actions
        transport: {
            read: {
                url: readUrl,
                type: "POST",
                contentType: "application/json"
            },
            parameterMap: function (options, operation) {
                if (operation === "read") {

                    var extendedK = new ExtendedKendo();
                    extendedK.ParseOriginalKendo(options, true, employeeNumber);

                    // convert the parameters to a json object
                    return kendo.stringify(extendedK);
                }

                // ALWAYS return options
                return options;
            }
        },

        // the schema defines the schema of the JSON coming
        // back from the server so the datasource can parse it
        schema: {

            // the array of repeating data elements (employees)
            data: "Data",

            // the total count of records in the whole dataset. used
            // for paging.
            total: "Count",

            model: {

                fields: columns
            },

            parse: function (response) {
                if (response.Data !== undefined) {
                    for (var i = 0; i < response.Data.length; i++) {
                        response.Data[i].toDate;
                        if (response.Data[i].toDate !== undefined) {
                            if (response.Data[i].toDate === "/Date(253370745000000)/") {
                                response.Data[i].toDate = null;
                            }
                        }
                    }

                }

                return response;
            },
            // map the errors if there are any. this automatically raises the "error" 
            // event
            errors: "Errors"
        },
        error: function (e) {

            console.log(e.statusText);
        },

        // the number of records to show per page
        pageSize: 20,
        // do paging on the server
        serverPaging: true,
        // do sorting on the server
        serverSorting: true,

    });


    $("#dvAdditional").kendoGrid({
        dataSource: source,
        pageable: true,
        sortable: true,
        scrollable: false,
        columns: gridColumns,
       
    });

}

// Custom created objects
function errorHandle(args, grid) {
    if (args.errors) {
        grid.one("dataBinding", function (e) {
            e.preventDefault();   // cancel grid rebind if error occurs                             

            for (var error in args.errors) {
                showMessage(grid.editable.element, error, args.errors[error].errors);
            }
        });
    }
}

function showMessage(container, name, errors) {
    //add the validation message to the form
    container.find("[data-valmsg-for=" + name + "]")
        .replaceWith($(validationMessageTmpl({ field: name, message: errors[0] })))
}

function onRequestEnd(e, dataSource) {
    //RequestEnd event handler code
    if (e.type == "update") {
        dataSource.read();
    }
    if (e.type == "insert") {
        dataSource.read();
    }
}

function ExtendedKendo() {
    this.take = '';
    this.skip = '';
    this.pageSize = '';
    this.group = undefined;
    this.searchTerm = '';
    this.searchType = '';
    this.employeeNumber = '';
    this.filter = undefined;
    this.searchGender = '';
    this.searchDepartment = '';
    this.searchOldEmployee = false;
    this.searchDepartmentNumber = '';
}

function LoginModel() {
    this.UserName = '';
    this.Password = '';

}

ExtendedKendo.prototype.ParseOriginalKendo = function (kendoObject, empFlag, employeeNumber, searchDepartmentNumber, searchOld) {
    this.take = kendoObject.take;
    this.skip = kendoObject.skip;
    this.pageSize = kendoObject.pageSize;
    this.group = kendoObject.group;
    this.searchTerm = ($("#txtbxSearchMulti").val() !== undefined) ? $("#txtbxSearchMulti").val() : $("#txtSearch").val();
    this.searchGender = $("#cmbbxGender").val();
    this.searchDepartment = $("#cmbbxDepartment").val();
    this.searchTitle = $("#cmbbxTitle").val();
    this.searchOldEmployee = (searchOld !== undefined) ? searchOld : false;
    this.searchDepartmentNumber = searchDepartmentNumber;
    if (empFlag === true) {
        this.employeeNumber = employeeNumber;
    }
    this.filter = kendoObject.filter;

};


/// Kendo Chart test
function createChart(dataValues, title) {
    $("#chart").kendoChart({
        theme: $(document).data("kendoSkin") || "metro",
        title: {
            text: title
        },
        legend: {
            position: "bottom",
            labels: {
                template: "#= text # (#= value #%)"
            }
        },
        seriesDefaults: {
            labels: {
                visible: true,
                format: "{0}%"
            }
        },
        dataSource: {
            data: dataValues,//[{ "source": "Male", "percentage": 60.4958, "explode": true }, { "source": "Female", "percentage": 39.5042, "explode": true }]
        },
        series: [{
            type: "pie",
            field: "percentage",
            categoryField: "source",
            explodeField: "explode"
        }],
        tooltip: {
            visible: true,
            template: "${ category } - ${ value }%"
        }
    });
}

///// Uploading an image logic

var x = 0, y = 0, w = 0, h = 0;
var imageHandler = "/Helpers/ImageHandler.ashx?id=";

$(function () {
    // Uploadify File Upload System
    // SessionSync data is sent in scriptData for security reasons, see UploadifySessionSync() in global.asax
    var UploadifyAuthCookie = '<% = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>';
    var UploadifySessionId = '<%= Session.SessionID %>';

    $("#fuFileUploader").uploadify({
        'hideButton': true,       // We use a trick below to overlay a fake html upload button with this hidden flash button                         
        'wmode': 'transparent',
        'uploader': uploadifyUploader,
        'cancelImg': uploadifyCancelImg,
        'buttonText': 'Upload File',
        'script': uploadifyScript,
        'multi': true,
        'auto': true,
        'fileExt': '*.jpg;*.gif;*.png;*.jpeg',
        'fileDesc': 'Image Files',
        'scriptData': { RequireUploadifySessionSync: true, SecurityToken: UploadifyAuthCookie, SessionId: UploadifySessionId },
        'onComplete': function (event, ID, fileObj, response, data) {
            response = $.parseJSON(response);
            if (response.Status == 'OK') {
                $("#imgUploadedImage").attr("src", imageHandler + response.Id);
                $("#dvId").dialog('open');
                $("#pnlUpload").hide();
                $("#pnlUploadedImage").show();

                $('#imgUploadedImage').Jcrop({
                    onChange: setCoords,
                    onSelect: setCoords
                    //minSize: [200, 200],
                    //maxSize: [200, 200]
                });
            }
        }
    });
});

function onUploadError(e) {
    // Show the error
    $('#lblMethodError').text(xhr.responseText);
    $('#lblMethodError').show("Failed to upload image.");;
}

function onUploadSuccess(e) {
    // Handle the upload event
    $('#lblMethodError').hide();
    $("#pnlUploadedImage").show();
    $("#imgUploadedImage").attr("src", imageHandler + e.response.imageId);
    $('#imgUploadedImage').Jcrop({
        onChange: setCoords,
        onSelect: setCoords,
        minSize: [200, 200],
        maxSize: [200, 200]
    });
}

function setCoords(c) {
    x = c.x;
    y = c.y;
    w = c.w;
    h = c.h;
};

function cropImage() {
    $.ajax({
        url: "/Image/CropImage",
        type: "POST",
        data: { x: x, y: y, w: w, h: h },
        success: function (data) {
            $("#pnlUploadedImage").hide();
            $('#lblMethodError').hide();
            $("#pnlNewImage").show();
            $("#imgNewImage").attr("src", imageHandler + data);
        },
        error: function (xhr, status, error) {
            // Show the error
            $('#lblMethodError').text(xhr.responseText);
            $('#lblMethodError').show();
        }
    });

}

function resizeImage() {
    // Call the server side function to resize the image
    $.ajax({
        url: "/Image/ResizeImage",
        type: "POST",
        success: function (data) {
            $("#pnlUploadedImage").hide();
            $('#lblMethodError').hide();
            $("#pnlNewImage").show();
            $("#imgNewImage").attr("src", imageHandler + data);
        },
        error: function (xhr, status, error) {
            // Show the error
            $('#lblMethodError').text(xhr.responseText);
            $('#lblMethodError').show();
        }
    });
}

$(document).ready(function () {
    //init();
    $("#btnUpload").click(function () {
        $("#fuFileUploader").click();
       // alert('heehaw');
    });
    $("#dvId").dialog({
        autoOpen: false,
        width: 600,
        title: "Edit Image",
        close: function (event, ui) { location.reload(); },
        buttons: {
            "Update Profile Picture": function () {
                // add the image to the other div that is nested within the employee 
                // form

                $.ajax({
                    url: "/Image/SaveImage",
                    type: "POST",
                    success: function (data) {
                        //$('#lblMethodError').hide();
                        //$("#pnlNewImage").show();
                        //$("#imgNewImage").attr("src", imageHandler + data);
                        alert('Upload Success');

                    },
                    error: function (xhr, status, error) {

                        // Show the error
                        $('#lblMethodError').text(xhr.responseText);
                        $('#lblMethodError').show();
                    }
                });

                $("#pnlUpload").show();
                $("#imgUploadedImage").attr("src", '');
                $("#dvId").dialog('close');
                location.reload();
            },
            "Cancel": function () {
                // discards the image
                $("#dvId").dialog('close');
                $("#imgUploadedImage").attr("src", '');
                location.reload();
            }
        }
    });
});

// HTML 5 Canvas generation
//var ctx;
//var factorvalue = 0.15;
//var fontfamily = "65px 'Gill Sans Ultra Bold', sans-serif";
//function init() {
//    ctx = document.getElementById('canvas').getContext('2d');
//    ctx.font = fontfamily;
//    ctx.save();
//    dologo();
//}
//function dologo() {
//    var offsety = 80;
//    ctx.restore();
//    ctx.save();
//    ctx.clearRect(0, 0, 600, 400);
//    ctx.scale(factorvalue, factorvalue);
//    ctx.fillText("HR Application", 31, 60);
//    ctx.translate(0, offsety);

//    // 5 sided orange background
//    ctx.fillStyle = "#E34C26";
//    ctx.beginPath();
//    ctx.moveTo(39, 250);
//    ctx.lineTo(17, 0);
//    ctx.lineTo(262, 0);
//    ctx.lineTo(239, 250);
//    ctx.lineTo(139, 278);
//    ctx.closePath();
//    ctx.fill();

//    // right hand, lighter orange part of the background
//    ctx.fillStyle = "#F06529";
//    ctx.beginPath();
//    ctx.moveTo(139, 257);
//    ctx.lineTo(220, 234);
//    ctx.lineTo(239, 20);
//    ctx.lineTo(139, 20);
//    ctx.closePath();
//    ctx.fill();

//    // light gray, left hand side part of the five
//    ctx.fillStyle = "#EBEBEB";
//    ctx.beginPath();
//    ctx.moveTo(139, 113);
//    ctx.lineTo(98, 113);
//    ctx.lineTo(96, 82);
//    ctx.lineTo(139, 82);
//    ctx.lineTo(139, 51);
//    ctx.lineTo(62, 51);
//    ctx.lineTo(70, 144);
//    ctx.lineTo(139, 144);
//    ctx.closePath();
//    ctx.fill();

//    ctx.beginPath();
//    ctx.moveTo(139, 193);
//    ctx.lineTo(105, 184);
//    ctx.lineTo(103, 159);
//    ctx.lineTo(72, 159);
//    ctx.lineTo(76, 207);
//    ctx.lineTo(139, 225);
//    ctx.closePath();
//    ctx.fill();

//    // white, right hand side of the 5
//    ctx.fillStyle = "#FFFFFF";
//    ctx.beginPath();
//    ctx.moveTo(139, 113);
//    ctx.lineTo(139, 144);
//    ctx.lineTo(177, 144);
//    ctx.lineTo(173, 184);
//    ctx.lineTo(139, 193);
//    ctx.lineTo(139, 225);
//    ctx.lineTo(202, 207);
//    ctx.lineTo(210, 113);
//    ctx.closePath();
//    ctx.fill();

//    ctx.beginPath();
//    ctx.moveTo(139, 51);
//    ctx.lineTo(139, 82);
//    ctx.lineTo(213, 82);
//    ctx.lineTo(216, 51);
//    ctx.closePath();
//    ctx.fill();


//}

//function changescale(val) {
//    factorvalue = val / 100;
//    dologo();
//}

function RemoveSalary(e) {
    return '<a class="k-button" href="#" id="lnkRemoveSalary" onClick="return removeCurrent(\'salary\')">Remove Last Salary</a>';
};

function RemoveTitle(e) {
    return '<a class="k-button" href="#" id="lnkRemoveTitle" onClick="return removeCurrent(\'title\')">Remove Last Title</a>';
};

// Function that removes the last salary from the system
// based on the user's employee number. This is to ensure that
// a salary that was entered wrong would be able to be removed
function removeCurrent(value) {    
    var grid = $(gridName).data("kendoGrid");
    var text = null;   
    var employeeNumber = getEmployeeNumberFromMainGrid(gridName);
    var subgrid = null;
    var url = null;

    // check if the branch to be used is either salary or the title
    if (value === "salary") {
        url = "/Employee/RemoveSalary";
        subgrid = "#salaryDetails";
    }
    else if(value === "title") {
        url = "/Employee/RemoveTitle";
        subgrid = "#titleHistory";
    }
    
    var params = {}
    params.employeeNumber = employeeNumber;

    // before running the ajax call, check if there are columns in 
    // the respective grid
    var dataLength = $(subgrid).data("kendoGrid")._data.length;

    // if there are items in a grid
    if (dataLength > 0) {
        $.ajax({
            url: url,
            dataType: 'json',
            async: false,
            data: params,
            success: function (result) {
                alert('JSON return was successful');
            }
        });

        $(subgrid).data("kendoGrid").dataSource.read();
    }
    else {
        alert('No items in the grid');
    }

   

    return false;
}

function showImage(e) {
    wnd = $("#dvImageResize").kendoWindow({
                           title: "Profile Picture",
                           modal: true,
                           visible: false,
                           resizable: false,
                           width: 300
                       }).data("kendoWindow");

    var employeeNumber = getEmployeeNumberFromMainGrid(gridName);
    if (employeeNumber !== undefined) {
        var imageCreation = "<img src="+imageRepository+employeeNumber+" style=\"height: 90%; width: 90%;\" />";
        alert(employeeNumber);        
        wnd.content(imageCreation);
        wnd.center().open();
        wnd.wrapper.css({ transform: "scale(1)" });
        wnd.wrapper.css("-webkit-transform", "");
    }
   
    return false;
}


function getEmployeeNumberFromMainGrid(gridName) {
    var selectedrow = $(gridName).find("tbody tr.k-state-selected");
    if ($(gridName).data("kendoGrid") !== undefined) {
        var dataItem = $(gridName).data("kendoGrid").dataItem(selectedrow);
        var datajson = dataItem.toJSON();
        var employeeNumber = datajson.employeeNumber;
        return employeeNumber;
    }
  
    return undefined;
    
}